#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>


Myfile* Buyfile(int fd,int flag)
{
  Myfile* f = (Myfile*)malloc(sizeof(Myfile));
  if(f == NULL) return NULL;
  f -> fileno = fd; 
  f -> flag = flag;
  f -> bufferlen = 0;
  f -> flush_method = 0;
  f->flush_method = LINE_FLUSH;
  memset(f->outbuffer, 0, sizeof(f->outbuffer));
  return f;
}




Myfile* Myopen(const char* path,const char* mode)
{
  int fd = -1; //记录初始的文件描述符，为了判断这个文件是否正常的打开了
  int flag =0;  //记录文件打开的方式 
  if(strcmp(mode,"w") == 0)  //和字符串比较  //进入删除数据然后重新输入模式
  {
    flag = O_CREAT | O_WRONLY | O_TRUNC;
    fd = open(path,flag,0666);
  }
  else if(strcmp(mode,"a") == 0)  //进入追加模式
  {
    flag = O_CREAT | O_WRONLY  |O_APPEND;
    fd = open(path,flag,0666);
  }
  else if(strcmp(mode,"r") == 0) //进入只读模式
  {
    flag = O_RDWR;
    fd = open(path,flag,0666);
  }
  if(fd < 0) return NULL;
  return Buyfile(fd,flag);
}
void Myclose(Myfile* file)
{
  if(file ->fileno < 0) return; //证明此时的文件并没有被打开
  Myflush(file);
  close(file ->fileno); //把文件直接关掉就可以了
  free(file);
  file = NULL; //避免内存泄露
}
int Mywrite(Myfile* file , void* str, int len)
{
  //拷贝数据
  memcpy(file ->outbuffer +file->bufferlen,str,len);
  file->bufferlen += len;
  //看看此时的空间是否满足了可以刷新条件
  if(file ->flush_method & LINE_FLUSH && file ->outbuffer[file->bufferlen - 1] == '\n')
  {
    Myflush(file);
  }
  return 0;
}
void Myflush(Myfile*file)
{
  if(file ->bufferlen <= 0)  return; //证明此时的缓冲区没数据
  //把数据从用户拷贝到文件内部的缓冲区中(内核缓冲区)
  int n = write(file ->fileno,file->outbuffer,file->bufferlen);
  (void)n;
  fsync(file->fileno);
  file -> bufferlen = 0;
}
